//! server模块重构测试的独立运行器

#[cfg(test)]
mod tests {
    use crate::server::enhanced_traits::*;
    use crate::storage::RedisServerMode;
    use async_trait::async_trait;

    /// Mock配置实现 - 用于测试ServerConfig trait
    #[derive(Debug, Clone)]
    struct MockServerConfig {
        mode: RedisServerMode,
        bind_address: String,
        should_fail_validation: bool,
    }

    impl MockServerConfig {
        fn new(mode: RedisServerMode, bind_address: String) -> Self {
            Self {
                mode,
                bind_address,
                should_fail_validation: false,
            }
        }
        
        fn with_validation_failure(mut self) -> Self {
            self.should_fail_validation = true;
            self
        }
    }

    #[async_trait]
    impl ServerConfig for MockServerConfig {
        fn mode(&self) -> RedisServerMode {
            self.mode
        }
        
        fn bind_address(&self) -> &str {
            &self.bind_address
        }
        
        fn validate(&self) -> Result<(), String> {
            if self.should_fail_validation {
                Err("Mock validation failed".to_string())
            } else {
                Ok(())
            }
        }
        
        fn extra_config(&self) -> Option<&dyn std::any::Any> {
            None
        }
        
        fn clone_config(&self) -> Box<dyn ServerConfig> {
            Box::new(self.clone())
        }
    }

    #[tokio::test]
    async fn test_server_config_basic_functionality() {
        let config = MockServerConfig::new(
            RedisServerMode::Standalone, 
            "127.0.0.1:6379".to_string()
        );
        
        assert_eq!(config.mode(), RedisServerMode::Standalone);
        assert_eq!(config.bind_address(), "127.0.0.1:6379");
        assert!(config.validate().is_ok());
        assert!(config.extra_config().is_none());
    }
    
    #[tokio::test]
    async fn test_server_config_validation_failure() {
        let config = MockServerConfig::new(
            RedisServerMode::Cluster, 
            "127.0.0.1:7000".to_string()
        ).with_validation_failure();
        
        assert!(config.validate().is_err());
        assert_eq!(config.validate().unwrap_err(), "Mock validation failed");
    }

    #[tokio::test]
    async fn test_server_config_clone() {
        let config = MockServerConfig::new(
            RedisServerMode::Standalone, 
            "127.0.0.1:6379".to_string()
        );
        
        let cloned = config.clone_config();
        assert_eq!(cloned.mode(), config.mode());
        assert_eq!(cloned.bind_address(), config.bind_address());
    }

    /// Mock服务生命周期实现 - 用于测试ServiceLifecycle trait
    #[derive(Debug)]
    struct MockServiceLifecycle {
        name: String,
        is_running: std::sync::Arc<std::sync::atomic::AtomicBool>,
        start_count: std::sync::Arc<std::sync::atomic::AtomicUsize>,
        stop_count: std::sync::Arc<std::sync::atomic::AtomicUsize>,
        should_fail_start: bool,
        should_fail_stop: bool,
    }

    impl MockServiceLifecycle {
        fn new(name: String) -> Self {
            Self {
                name,
                is_running: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
                start_count: std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)),
                stop_count: std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)),
                should_fail_start: false,
                should_fail_stop: false,
            }
        }
        
        fn with_start_failure(mut self) -> Self {
            self.should_fail_start = true;
            self
        }
        
        fn get_start_count(&self) -> usize {
            self.start_count.load(std::sync::atomic::Ordering::Relaxed)
        }
        
        fn get_stop_count(&self) -> usize {
            self.stop_count.load(std::sync::atomic::Ordering::Relaxed)
        }
    }

    #[async_trait]
    impl ServiceLifecycle for MockServiceLifecycle {
        fn service_name(&self) -> &'static str {
            // 为了简化测试，这里使用静态字符串
            "MockService"
        }
        
        async fn start(&mut self) -> std::io::Result<()> {
            self.start_count.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
            
            if self.should_fail_start {
                return Err(std::io::Error::new(
                    std::io::ErrorKind::Other,
                    "Mock start failure"
                ));
            }
            
            self.is_running.store(true, std::sync::atomic::Ordering::Relaxed);
            Ok(())
        }
        
        async fn stop(&mut self) -> std::io::Result<()> {
            self.stop_count.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
            
            if self.should_fail_stop {
                return Err(std::io::Error::new(
                    std::io::ErrorKind::Other,
                    "Mock stop failure"
                ));
            }
            
            self.is_running.store(false, std::sync::atomic::Ordering::Relaxed);
            Ok(())
        }
        
        fn is_running(&self) -> bool {
            self.is_running.load(std::sync::atomic::Ordering::Relaxed)
        }
        
        async fn graceful_shutdown(&mut self, _timeout_secs: u64) -> std::io::Result<()> {
            self.stop().await
        }
    }

    #[tokio::test]
    async fn test_service_lifecycle_basic_operations() {
        let mut service = MockServiceLifecycle::new("test_service".to_string());
        
        // 初始状态
        assert!(!service.is_running());
        assert_eq!(service.get_start_count(), 0);
        assert_eq!(service.get_stop_count(), 0);
        
        // 启动服务
        assert!(service.start().await.is_ok());
        assert!(service.is_running());
        assert_eq!(service.get_start_count(), 1);
        
        // 停止服务
        assert!(service.stop().await.is_ok());
        assert!(!service.is_running());
        assert_eq!(service.get_stop_count(), 1);
    }

    #[tokio::test]
    async fn test_service_lifecycle_restart() {
        let mut service = MockServiceLifecycle::new("test_service".to_string());
        
        // 重启操作
        assert!(service.restart().await.is_ok());
        
        // 验证重启调用了stop和start
        assert!(service.is_running());
        assert_eq!(service.get_start_count(), 1);
        assert_eq!(service.get_stop_count(), 1);
    }

    #[tokio::test]
    async fn test_service_lifecycle_start_failure() {
        let mut service = MockServiceLifecycle::new("test_service".to_string())
            .with_start_failure();
        
        // 启动失败
        let result = service.start().await;
        assert!(result.is_err());
        assert_eq!(result.unwrap_err().to_string(), "Mock start failure");
        
        // 服务应该未运行
        assert!(!service.is_running());
        assert_eq!(service.get_start_count(), 1); // 尝试计数应该增加
    }

    /// Mock事件监听器 - 用于测试ServerEventListener trait
    #[derive(Debug)]
    struct MockEventListener {
        name: String,
        events_received: std::sync::Arc<std::sync::Mutex<Vec<ServerEvent>>>,
        should_fail: bool,
    }

    impl MockEventListener {
        fn new(name: String) -> Self {
            Self {
                name,
                events_received: std::sync::Arc::new(std::sync::Mutex::new(Vec::new())),
                should_fail: false,
            }
        }
        
        fn with_failure(mut self) -> Self {
            self.should_fail = true;
            self
        }
        
        fn get_received_events(&self) -> Vec<ServerEvent> {
            self.events_received.lock().unwrap().clone()
        }
        
        fn get_event_count(&self) -> usize {
            self.events_received.lock().unwrap().len()
        }
    }

    #[async_trait]
    impl ServerEventListener for MockEventListener {
        async fn on_event(&mut self, event: ServerEvent) -> Result<(), String> {
            if self.should_fail {
                return Err("Mock listener failure".to_string());
            }
            
            self.events_received.lock().unwrap().push(event);
            Ok(())
        }
        
        fn listener_name(&self) -> &str {
            &self.name
        }
    }

    /// Mock事件发布器 - 用于测试ServerEventPublisher trait
    #[derive(Debug)]
    struct MockEventPublisher {
        listeners: std::sync::Arc<std::sync::Mutex<Vec<std::sync::Arc<dyn ServerEventListener>>>>,
        published_events: std::sync::Arc<std::sync::Mutex<Vec<ServerEvent>>>,
        should_fail_publish: bool,
        should_fail_subscribe: bool,
    }

    impl MockEventPublisher {
        fn new() -> Self {
            Self {
                listeners: std::sync::Arc::new(std::sync::Mutex::new(Vec::new())),
                published_events: std::sync::Arc::new(std::sync::Mutex::new(Vec::new())),
                should_fail_publish: false,
                should_fail_subscribe: false,
            }
        }
        
        fn get_published_events(&self) -> Vec<ServerEvent> {
            self.published_events.lock().unwrap().clone()
        }
        
        fn get_listener_count(&self) -> usize {
            self.listeners.lock().unwrap().len()
        }
    }

    #[async_trait]
    impl ServerEventPublisher for MockEventPublisher {
        async fn subscribe(&mut self, listener: std::sync::Arc<dyn ServerEventListener>) -> Result<(), String> {
            if self.should_fail_subscribe {
                return Err("Mock subscribe failure".to_string());
            }
            
            self.listeners.lock().unwrap().push(listener);
            Ok(())
        }
        
        async fn unsubscribe(&mut self, listener_name: &str) -> Result<(), String> {
            let mut listeners = self.listeners.lock().unwrap();
            let original_len = listeners.len();
            listeners.retain(|listener| listener.listener_name() != listener_name);
            
            if listeners.len() == original_len {
                Err(format!("监听器未找到: {}", listener_name))
            } else {
                Ok(())
            }
        }
        
        async fn publish(&self, event: ServerEvent) -> Result<(), String> {
            if self.should_fail_publish {
                return Err("Mock publish failure".to_string());
            }
            
            self.published_events.lock().unwrap().push(event.clone());
            
            // 通知所有监听器（简化实现）
            let listeners = self.listeners.lock().unwrap();
            for listener in listeners.iter() {
                // 在真实实现中，这里需要处理可变性问题
                // 但为了简化测试，我们只是记录事件
                drop(listener);
            }
            
            Ok(())
        }
    }

    #[tokio::test]
    async fn test_event_publisher_subscribe_unsubscribe() {
        let mut publisher = MockEventPublisher::new();
        let listener = std::sync::Arc::new(MockEventListener::new("test_listener".to_string()));
        
        // 初始状态
        assert_eq!(publisher.get_listener_count(), 0);
        
        // 订阅监听器
        assert!(publisher.subscribe(listener.clone()).await.is_ok());
        assert_eq!(publisher.get_listener_count(), 1);
        
        // 取消订阅
        assert!(publisher.unsubscribe("test_listener").await.is_ok());
        assert_eq!(publisher.get_listener_count(), 0);
        
        // 取消不存在的监听器应该失败
        let result = publisher.unsubscribe("nonexistent").await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_event_publisher_publish() {
        let publisher = MockEventPublisher::new();
        
        let event = ServerEvent::Starting { mode: RedisServerMode::Standalone };
        assert!(publisher.publish(event.clone()).await.is_ok());
        
        let published_events = publisher.get_published_events();
        assert_eq!(published_events.len(), 1);
        
        match &published_events[0] {
            ServerEvent::Starting { mode } => {
                assert_eq!(*mode, RedisServerMode::Standalone);
            }
            _ => panic!("事件类型错误"),
        }
    }

    #[tokio::test]
    async fn test_server_event_types() {
        // 测试各种事件类型
        let events = vec![
            ServerEvent::Starting { mode: RedisServerMode::Standalone },
            ServerEvent::Started { 
                mode: RedisServerMode::Standalone, 
                bind_addr: "127.0.0.1:6379".to_string() 
            },
            ServerEvent::Stopping { mode: RedisServerMode::Standalone },
            ServerEvent::Stopped { mode: RedisServerMode::Standalone },
            ServerEvent::Error { 
                message: "Test error".to_string(), 
                recoverable: true 
            },
            ServerEvent::ConfigChanged { 
                old_mode: RedisServerMode::Standalone, 
                new_mode: RedisServerMode::Cluster 
            },
        ];
        
        // 确保所有事件都可以被克隆和调试输出
        for event in events {
            let cloned = event.clone();
            println!("{:?}", cloned); // 验证Debug trait
        }
    }
}